package com.liusr.template.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;

/**
 * @author Liusr
 * @date 2023/1/23
 * @package com.liusr.template.config
 * @Description: swagger文档控制类
 */
@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class SwaggerConfig {
	/*引入Knife4j提供的扩展类*/
	private final OpenApiExtensionResolver openApiExtensionResolver;
	@Autowired
	public SwaggerConfig(OpenApiExtensionResolver openApiExtensionResolver){
		this.openApiExtensionResolver = openApiExtensionResolver;
	}

	@Autowired
	private Environment environment;

	@Bean(value = "docket")
	public Docket docket() {
		// 设置显示的swagger环境信息
		Profiles profiles = Profiles.of("dev");
		// 判断是否处在自己设定的环境当中
		boolean flag = environment.acceptsProfiles(profiles);

		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				// 配置api文档的分组
				.groupName("liusr's group")
				// 配置是否开启swagger
				.enable(flag)
				.select()
				//配置扫描路径
				.apis(RequestHandlerSelectors.basePackage("com.liusr"))
				// 配置过滤哪些
				.paths(PathSelectors.any())
				.build()
				// 为了区分开发者在构建自定义文档时，在不同的Docket逻辑分组下进行区别显示
				.extensions(openApiExtensionResolver.buildExtensions("md"));
	}

	/**
	 * api基本信息
	 * @return ApiInfo
	 */
	private ApiInfo apiInfo() {
		return new ApiInfo("template swagger",
				"测试knife4j-ui",
				"v1.0",
				"http://127.0.0.1",
				//作者信息
				new Contact("liusr", "http://mail.qq.com", "xxxxxxxx@qq.com"),
				"Apache 2.0",
				"http://www.apache.org/licenses/LICENSE-2.0",
				new ArrayList());
	}
}
